<?php
/**
 * Created by PhpStorm.
 * User: L
 * Date: 20.10.30
 * Time: 17:31
 */

namespace App;


use App\Models\Server;
use Illuminate\Support\Facades\Storage;

class SSHApi implements FileManege
{
    protected $ssh2;

    public function __construct(string $host,int $post,string $username,string $password)
    {
        $this->ssh2=new SSH2();
        $this->ssh2=$this->ssh2->connect($username,$password,$host,$post);
    }

    public function check()
    {
        $this->ssh2->exec('uname -a');
        $res=$this->ssh2->get();
        return $res;
    }

    public function getInfo()
    {
        // TODO: Implement getInfo() method.
    }

    protected function getConn(){
        return $this->ssh2->getConnect();
    }

    public function GetFileBody(string $path)
    {
        $connection=$this->getConn();
        $sftp = ssh2_sftp($connection);
        try {
            $content = file_get_contents("ssh2.sftp://" . intval($sftp).$path);
            return[
                'status'=>true,
                'data'=>$content
            ];
        }catch (\Exception $e){
            return[
                'status'=>false,
                'msg'=>'文件不存在'
            ];
        }


    }

    public function SaveFileBody(string $path, string $data,Server $server=null)
    {
        //将string保存到本地，然后上传到服务器
        Storage::put("server/{$server->id}{$path}",$data);
        $path_local=storage_path("app/server/{$server->id}{$path}");
        //上传文件
        $res=$this->ssh2->run_send($path_local, $path);
        return $res;
    }

    public function GetDir(string $path)
    {

    }

    public function GetDirList(string $path, string $search)
    {
        $comm="find $path -name *$search";

        $this->ssh2->exec($comm);
        $res=$this->ssh2->get();

        $list=explode ("\n",$res);
        $flist=[];
        foreach ($list as $item){
            if ($item!==''){
                array_push($flist,['filename'=>$item]);
            }
        }

        return ['LIST'=>$flist,'path'=>$path];
    }

    public function CreateDir(string $path)
    {
        // TODO: Implement CreateDir() method.
    }

    public function CreateFile(string $path)
    {
        // TODO: Implement CreateFile() method.
    }

    public function DeleteFile(string $path)
    {
        // TODO: Implement DeleteFile() method.
    }

    public function MvFile(string $path, string $nameOld, string $nameNew)
    {
        // TODO: Implement MvFile() method.
    }
}
